package com.demo.core.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.demo.common.Utils;
import com.demo.core.cache.CacheKey;
import com.demo.core.cache.CacheWrapper;
import com.demo.core.dao.FolderDao;
import com.demo.core.dao.impl.base.PageCoreDaoSupport;
import com.demo.core.model.Folder;
import com.demo.core.model.support.GeneralExecuteModel;

/**
 * 目录数据库访问层实现类
 * 
 * @author ryuu.kk
 */
public class FolderDaoImpl extends PageCoreDaoSupport<Folder, Long> implements FolderDao {
	/**
	 * 目录空间 
	 */
	protected final static String FOLDER_SPACE = "folderSpace.";
	/**
	 * 模型表名
	 */
	protected final static String TABLE_NAME = "T_CORE_FOLDER";
	/**
	 * 模型表主键ID
	 */
	protected final static String TABLE_PK_NAME = "ID";
	
	@Override
	public Long insert(Folder folder) {
		//创建一个唯一标示
		folder.setUuid(Utils.uuid());
		return super.insert(folder);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Folder> tree(Map<String, Object> params) {
		CacheKey key = null;
		List<Folder> result = null;
		CacheWrapper<CacheKey, Object> cache = null;
		
		if (isUseCache() && (cache = getCache()) != null) {
			key = new CacheKey();
			key.update("tree");
			key.update(params.hashCode());
			result = (List<Folder>) cache.get(key);
		}
		if (result == null) {
			result  = getSqlMapClientTemplate().queryForList(FOLDER_SPACE + "queryTree", params);
			if (isUseCache() && cache != null && result != null) {
				cache.put(key, result);
			}
		}
		return result;
	}

	@Override
	public int delete(Long id) {
		Map<String, Object> params = new HashMap<String, Object>();
		int cnt = 0;
		params.put("id", id);
		delete(params);
		if (params.containsKey("cnt")) {
			cnt = Integer.parseInt(params.get("cnt").toString());
		}
		return cnt;
	}
	@Override
	public boolean exists(String uuid) {
		
		return find(uuid) != null;
	}
	
	@Override
	public Folder find(String uuid) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uuid", uuid);
		List<Folder> folderList = super.select(params);
		return (folderList != null && folderList.size() > 0) ? folderList.get(0) : null;
	}
	
	@Override
	protected String nameSpace() {
		return FOLDER_SPACE;
	}
	@Override
	protected void doInit(GeneralExecuteModel<Long> model) {
		model.setPk(TABLE_PK_NAME);
		model.setTable(TABLE_NAME);
	}
}
